package api

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/pquerna/otp/totp"
	"image/png"
	"net/http"
)

type User struct {
	Username string
	Password string
	OTPKey   string
}

var users = make(map[string]User)

func generateOTPQr(issuer string, newUser User) (string, error) {
	key, err := totp.Generate(totp.GenerateOpts{
		Issuer:      issuer,
		AccountName: newUser.Username,
	})
	if err != nil {
		return "", err
	}

	newUser.OTPKey = key.Secret()
	users[newUser.Username] = newUser

	img, err := key.Image(200, 200)
	if err != nil {
		return "", err
	}
	buf := new(bytes.Buffer)
	err = png.Encode(buf, img)
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("data:image/png;base64,%s", base64.StdEncoding.EncodeToString(buf.Bytes())), nil
}

func Register(c *gin.Context) {
	var newUser User
	if err := c.ShouldBindJSON(&newUser); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	issuer := "fc5856.com"
	// 使用前端传入的 accountName
	otpQrString, err := generateOTPQr(issuer, newUser)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"message": "User registered successfully", "qrCode": otpQrString})
}
